import {Component, ViewEncapsulation, Input, Output, EventEmitter, ViewChild} from '@angular/core';
import {Utility} from '../../../../../services/app.utility';
import {IdeaService} from '../../../../../services/app.idea';
import {UserService} from  '../../../../../services/app.user';
import {Observable} from 'rxjs';
import {BaThemeSpinner}  from '../../../../../theme/services';
import {Router} from '@angular/router';
import {FacebookHelper} from  '../../../../../common/app.facebook';
import {Constants} from '../../../../../common/app.constants';
import {Modal} from 'ngx-modal';
declare let toastr:any;
declare let $:any;
declare let Treant:any;

@Component({
    selector: 'cardIdea',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./cardIdea.scss'],
    templateUrl: './cardIdea.html',
})
export class cardIdea {
    start: number = 0;
    public CommentListOfIdea:any;
    public singleArray:any;


    @Input()
    public versioning:boolean;

    public viewDetailIdea:any;
    public abuseIdea:any;
    deleteIdeaId: string = '';
    public end:any;
    public check:any;
    @ViewChild('deleteIdeaModal')
    deleteIdeaModal: Modal;
    @Input()
    idea:any;
    @Input()
    userId:string;
    @Output()
    notifyParent:EventEmitter<any> = new EventEmitter();
    @Output()
    notifyParenttoAbuse:EventEmitter<any> = new EventEmitter();
  @Output()
  deleteIdeaNotify:EventEmitter<any> = new EventEmitter();
    @ViewChild('citationTree')
    private citationTreeModal:Modal;
    @ViewChild('citationTreeSingleKey')
    private citationTreeKeyModal:Modal;
    @Output()
    notifyParenttoProfile:EventEmitter<any> = new EventEmitter();
    @ViewChild('ViewDetailIdeaModel')
    public ViewDetailIdeaModel:Modal;
    @Output()
    notifyUserParent:EventEmitter<any> = new EventEmitter();
    @ViewChild('abuseModal')
    public abuseModal:Modal;
    @Input()
    constants:Constants;

    constructor(public facebookHelper:FacebookHelper, public router:Router, public utility:Utility, public spinner:BaThemeSpinner, public ideaService:IdeaService, public userService:UserService) {
        this.constants = new Constants();
        this.versioning = false;
        this.CommentListOfIdea = {
            skipCommentsItem: 0,
            commentsPerPage: 6,
        };
      this.check = 0;
      this.start = 0;
        // API call for get user info
      // todo
       /* this.userService.getuserInfo().subscribe(
            data => this.userInfoSuccess(data),
            error => {
            }
        );*/
    };

    // Share with fb function
    public sharewithFB(idea) {
        let tmp = document.createElement('DIV');
        tmp.innerHTML = idea.content;
        let data = tmp.textContent || tmp.innerText || '';
        this.facebookHelper.share(data);
    }


    // Convert Date to MM/DD/YY
    public formateDate(dates):any {
        return this.utility.getFormattedDateForTree(dates);
    }


    // Notify Parent for Open Modal PopUp
    sendNotification() {
        this.notifyParent.emit(this.idea);
    }

    // Notify parent for Abuse
    public setAbuse(idea) {
        this.notifyParenttoAbuse.emit(idea);
    }

    // View Profile function
    public viewProfile(idea) {
        this.utility.getUserProfileData(idea);
        this.router.navigate(['profile']);
        let data = {
            'target': this.constants.URL + 'profile',
            'value': 'profile',
            'action': 'redirect'
        };

        this.userService.setUserLogs(data).subscribe();
    }

    // Edit Idea and navigate on edit idea page
    public ShowEditIdea(idea) {
        this.utility.getEditIdea(idea);
        this.router.navigate(['editidea']);
    }

    // Adding Likes count
    public likesCount(idea) {
        this.spinner.showProgress();
        let ideasData = {
            'ideaId': idea._id,
            'voteType': 'like'
        };
        this.ideaService.ideaLikes(ideasData).subscribe(
            data => this.likesuccess(data, idea),
            error => this.likefail(error)
        );
    }

    // Function call if like successfully
    public likesuccess(result, idea) {
        this.spinner.hideProgress();

        if (result.voteType === 'like') {
            idea.likes = result.idea.likes;
            idea.dislikes = result.idea.dislikes;
            idea.points = result.idea.points;

            idea.isliked = true;
            idea.isdisliked = false;

            toastr.success(this.constants.LIKEIDEA);
        } else {
            idea.likes = result.idea.likes;
            idea.dislikes = result.idea.dislikes;
            idea.points = result.idea.points;

            idea.isliked = false;
            idea.isdisliked = false;
            toastr.success(this.constants.REMOVELIKEIDEA);
        }

    }

    // Function call if like failed
    public likefail(error) {
        this.spinner.hideProgress();
        toastr.error(error.error_message);
    }


    // Adding dislike count and call API
    public dislikesCount(idea) {
        this.spinner.showProgress();
        let ideasData = {
            'ideaId': idea._id,
            'voteType': 'dislike'
        };
        this.ideaService.ideaLikes(ideasData).subscribe(
            data => this.dislikesuccess(data, idea),
            error => this.dislikefail(error)
        );
    }

    // Function call if dislike successfully
    public dislikesuccess(result, idea) {

        this.spinner.hideProgress();

        if (result.voteType === 'dislike') {
            idea.likes = result.idea.likes;
            idea.dislikes = result.idea.dislikes;
            idea.points = result.idea.points;

            idea.isliked = false;
            idea.isdisliked = true;

            toastr.success(this.constants.DISLIKE);
        } else {
            idea.likes = result.idea.likes;
            idea.dislikes = result.idea.dislikes;
            idea.points = result.idea.points;

            idea.isdisliked = false;
            idea.isliked = false;
            toastr.success(this.constants.REMOVEDISLIKE);
        }
    }

    // Function call if dislike failed
    public dislikefail(error) {
        toastr.error(error.error_message);
        this.spinner.hideProgress();
    }


    // Adding Favourite Count and color red
    public favouriteCount(idea) {
        this.spinner.showProgress();
        let favouriteType = 'addFavourite';
        if (idea.isfavorite === true) {
            favouriteType = 'removeFavourite';
            idea.isfavorite = false;
        } else {
            favouriteType = 'addFavourite';
            idea.isfavorite = true;
        }
        let favouriteData = {
            'ideaId': idea._id,
            'favouriteType': favouriteType
        };
        this.ideaService.faouriteLikes(favouriteData).subscribe(
            data => this.favouritesuccess(data, idea),
            error => this.favouritefail(error)
        );
    }

    // Function call if favourite successfully
    public favouritesuccess(result, idea) {

        if (idea.isfavorite === true) {
            toastr.success(this.constants.FAVOURITEIDEA);
        } else {
            toastr.error(this.constants.REMOVEFAVOURITEIDEA);
        }
        this.spinner.hideProgress();
        result.isfavorite = !result.isfavorite;
    }

    // Function call if favourite failed
    public favouritefail(error) {
        toastr.error(error.error_message);
        this.spinner.hideProgress();
    }


    // array of citation tree
    public getBigTreeData(data):void {
      let input = {
        'target': 'Clicked on Cited array : ' + data,
        'action': 'left click'
      };
      this.userService.setUserLogs(input).subscribe();
        let inputData = {content: data};
        this.spinner.showProgress();
        this.ideaService.getCitationTreeData(inputData).subscribe(
            data => this.generateTree(data),
            error => {
            });
    }

    // single word citation tree
    public getTreeData(data):void {
      let input = {
        'target': 'Clicked on Cited word : ' + data,
        'action': 'left click'
      };
      this.userService.setUserLogs(input).subscribe();
        let inputData = {content: [data]};
        this.spinner.showProgress();
        this.ideaService.getCitationTreeData(inputData).subscribe(
            data => this.generateTreeSingleKey(data),
            error => {
            });
    }

    // Function call if user info API success and lock version
    public userInfoSuccess(data) {
      console.log("cardIdea");

        if (data.version === 'Version_1') {
            this.versioning = false;
        } else if (data.version === 'Version_2') {
            this.versioning = false;
        } else if (data.version === 'Version_4') {
            this.versioning = false;
        } else if (data.version === 'Version_6') {
            this.versioning = false;
        } else {
            this.versioning = true;
        }
    }

    // When click on cited word get citation tree
    ngAfterViewInit() {
        var self = this;
        setTimeout(() => {
            if (this.versioning) {
                // TODO 暂时取消词性标注
                /*$('.keywordColor').unbind().click(function () {
                    var word = $(this).text();
                    self.getTreeData(word);
                });*/
            } else {

            }
        }, 5000);
    }

    // When click on citation tree open idea modal
    ngAfterViewChecked() {
        var self = this;
        var userId, ideaId, showCitedContent, citedArray, date;
        $('.node-name').unbind().click(function () {
            userId = $(this).closest('div.nodeExample1').find('p:nth-child(6)').text();
            ideaId = $(this).closest('div.nodeExample1').find('p:nth-child(5)').text();
            if ((ideaId.length === 24) && (userId.length === 24)) {
                self.getfullIdea(ideaId, userId);
            } else {
                toastr.error(this.constants.IDNOTFOUND);
            }
        });

        $('.node-show').unbind().click(function () {
            showCitedContent = $(this).closest('div.nodeExample1').find('p:nth-child(4)').text();
            date = $(this).closest('div.nodeExample1').find('p:nth-child(3)').text();
            let CitedWord = showCitedContent.slice(1, showCitedContent.length - 1);
            let splitArray = CitedWord.trim();
            let citationTrim = splitArray.split(', ');
            let first_array = citationTrim;
            let input = {
              'target': 'expanding a branch of the citation tree',
              'action': 'left click'
            };
            self.userService.setUserLogs(input).subscribe();

            let inputData = {
                content: first_array,
                date: date
            };
            self.createSingleTree(inputData);
        });
        // TODO
        /*暂时取消词性标注*/

       /* $('.citationIdea').unbind().click(function () {
            citedArray = $(this).closest('div.citationIdea').find('p').text();
            let newArray = citedArray.split(',');
            self.getBigTreeData(newArray);
        });*/

    }


    // after click on show more call API
    public createSingleTree(data) {
        this.spinner.showProgress();
        this.ideaService.getCitationTreeData(data).subscribe(
            data => this.getSingleCitedData(data),
            error => {
            });
    }

    // after click on show more call API Result for citation tree
    public getSingleCitedData(data) {

        if (this.singleArray !== '') {
            let childNode = data;

            for (var i = 0; i < this.singleArray.children.length; i++) {
                if (this.singleArray.children[i].text.contact.indexOf(childNode.input) >= 0) {
                    this.singleArray.children[i].text.show = '';
                    this.singleArray.children[i].children = childNode.children;
                }
            }

            setTimeout(() => {
                let chartConfig = {

                    chart: {
                        container: '#tree-simple',
                        scrollbar: 'fancy',
                        siblingSeparation: 20,
                        subTeeSeparation: 60,
                        connectors: {
                            type: 'step'
                        },

                        node: {
                            HTMLclass: 'nodeExample1'
                        }

                    },

                    nodeStructure: this.singleArray

                };

                let chart = new Treant(chartConfig);
                setTimeout(() => {
                    this.spinner.hideProgress();
                }, 300);
              // start timer function call
              this.startCount();
            }, 500);
        }
    }


    // after click on cited word open single citation tree
    public generateTreeSingleKey(data) {
        if (data.children !== undefined) {
            this.citationTreeKeyModal.open();
            setTimeout(() => {
                let chartConfig = {
                    chart: {
                        container: '#tree-simple',
                        scrollbar: 'fancy',
                        siblingSeparation: 20,
                        subTeeSeparation: 60,
                        connectors: {
                            type: 'step'
                        },
                        node: {
                            HTMLclass: 'nodeExample1'
                        }
                    },
                    nodeStructure: data
                };
                let chart = new Treant(chartConfig);
                this.spinner.hideProgress();
              // start timer function call
              this.startCount();
            }, 500);
        } else {
            toastr.success(this.constants.IDNOTFOUND);
            this.spinner.hideProgress();
        }
    }


    // Function for generate citation tree for multiple array and add show more
    public generateTree(data) {
        this.singleArray = '';
        this.singleArray = data;

        this.spinner.hideProgress();
        if (this.singleArray.children !== undefined) {
            let CitedWord = this.singleArray.text.contact.slice(1, this.singleArray.text.contact.length - 1);
            let splitArray = CitedWord.trim();
            let citationTrim = splitArray.split(', ');
            let first_array = citationTrim;

            if (this.singleArray.children !== undefined) {
                if (first_array.length > 1) {
                    for (let i = 0; i < this.singleArray.children.length; i++) {
                        this.singleArray.children[i].text.show = 'Show More';
                    }
                }
            }


            this.citationTreeModal.open();
            setTimeout(() => {
                let chartConfig = {
                    chart: {
                        container: '#tree-simple',
                        scrollbar: 'fancy',
                        siblingSeparation: 20,
                        subTeeSeparation: 60,
                        connectors: {
                            type: 'step'
                        },

                        node: {
                            HTMLclass: 'nodeExample1'
                        }
                    },
                    nodeStructure: this.singleArray

                };
                let chart = new Treant(chartConfig);
                setTimeout(() => {
                    this.spinner.hideProgress();
                }, 300);
            }, 500);
        } else {
            toastr.success(this.constants.IDNOTFOUND);
            this.spinner.hideProgress();
        }
    }

    // code for idea modal
    getfullIdea(idea, user) {
        let data1 = {
            'idea': idea,
            'user': user
        };
        this.notifyUserParent.emit(data1);
        this.spinner.showProgress();
        let input = {
            ideaId: idea,
            userId: user
        };
        this.ideaService.getIdeaIdForAbuse(input).subscribe(
            data => this.getIdeaSuccess(data, input),
            error => this.getIdeaFail(error)
        );
    }

    // Function call when abuse idea successfully
    public getIdeaSuccess(ideainfo, input) {
        this.getIdeaComments(ideainfo, input);
    }

    // Function call when abuse idea failed
    public getIdeaFail(error) {
        console.log(error);
    }

    // adding comment function call
    public getIdeaComments(ideainfo, input) {
        let cardData = {
            'ideaId': input.ideaId,
            'skipItem': this.CommentListOfIdea.skipCommentsItem,
            'itemsperPage': this.CommentListOfIdea.commentsPerPage,
            'sortParameter': 'createdAt',
            'sortOrder': 'descending'
        };
        this.ideaService.getcardComment(cardData).subscribe(
            data => this.getcommentsuccess(data, ideainfo),
            error => this.getcommentfail(error)
        );

    }

    // Function call if comment success and increase count
    public getcommentsuccess(data, ideainfo) {

        this.ViewDetailIdeaModel.open();
        this.spinner.hideProgress();

        if (ideainfo.citationArray !== undefined) {
            for (let y = 0; y < ideainfo.citationArray.length; y++) {
                ideainfo.content = ideainfo.content.replace(ideainfo.citationArray[y], '<span class="keywordColorNew">' + ideainfo.citationArray[y] + '</span>');
            }
        }
        let modalData = [];
        modalData[0] = ideainfo;
        modalData[0].data = data;
        this.viewDetailIdea = modalData[0];
        if (this.utility.clickFromProfile) {
            this.ViewDetailIdeaModel.open();
        }

      let input = {
          'target': 'Expanding the idea post:' + ideainfo.title,
          'action': 'left click'
        };
        this.userService.setUserLogs(input).subscribe(
        data => this.ideaModalsuccess(data, ideainfo[0].title)
      );
    }
// User log for click on idea title
  public ideaModalsuccess(output, ideaTitle) {

      let input = {
        'target': ideaTitle,
        'action': 'left click'
      };
      this.userService.setUserLogs(input).subscribe();
    }
    // Function call if comment API return error
    public getcommentfail(data) {
        this.spinner.hideProgress();
    }

    // Fuction call when idea modal close and clear view
    public refreshActivity() {
        this.ViewDetailIdeaModel.close();
    }

    // Fuction call for open notification abuse modal
    getNotificationModal(idea) {
        this.abuseIdea = idea;
        this.abuseModal.open();
    }

    // Fuction call for close notification abuse modal
    getNotificationAbuseModal(evt) {
        this.abuseIdea = null;
        this.abuseModal.close();
    }

    // Fuction call for close citation tree and clear their content
    public closeCitationTree() {
        $('#tree-simple .nodeExample1').remove();
        $('path').remove();
        this.citationTreeModal.close();
        this.spinner.hideProgress();
      // To stop count function call
      this.stopCount();
    }

    // Fuction call for close citation tree generated from array and clear their content
    public closeCitationTreeDialog() {
        $('#tree-simple .nodeExample1').remove();
        $('path').remove();
        this.citationTreeKeyModal.close();
        this.spinner.hideProgress();
      // To stop count function call
      this.stopCount();
    }
  deleteParticularIdea(){
    this.spinner.show();
    let deleteIdea = {
      ideaId: this.deleteIdeaId
    };
    this.ideaService.deleteIdea(deleteIdea).subscribe(
      data => this.deleteIdeasuccess(data),
      error => this.deleteIdeafail(error)
    );
  }
  deleteIdea(idea){
    this.deleteIdeaModal.open();
    this.deleteIdeaId = idea._id;
  }
  deleteIdeasuccess(result){
    this.deleteIdeaModal.close();
    this.spinner.hide();
    this.deleteIdeaNotify.emit({});
    toastr.success("Idea deleted successfully");
  }
  deleteIdeafail(error){
    this.spinner.hide();
    toastr.error(error);
  }

  // To call every 1 sec for count how much time we spent on this page
  public  timedCount() {
    this.start = this.start + 1;
    this.end = setTimeout(() => {
      this.timedCount()
    }, 1000);
  }

  // To function for start timstamp count
  public startCount() {
    if (!this.check) {
      this.check = 1;
      this.timedCount();
    }
  }

  // To function for stop timstamp count
  public stopCount() {
    clearTimeout(this.end);
    this.check = 0;
  }
}
